package com.yx.louti.advice;

import com.yx.louti.globalException.model.HttpErrorResult;
import com.yx.louti.globalException.model.HttpResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 使用 @ControllerAdvice & ResponseBodyAdvice
 * 拦截Controller方法默认返回参数，统一处理返回值/响应体
 */
@RestControllerAdvice
@Order(value = 1)
public class HttpResponseResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> arg1) {
        com.yx.louti.annotation.HttpResponseResult apiEncrypt = parameter.getMethodAnnotation(com.yx.louti.annotation.HttpResponseResult.class);
        com.yx.louti.annotation.HttpResponseResult apiEncryptClass = parameter.getDeclaringClass().getAnnotation(com.yx.louti.annotation.HttpResponseResult.class);
        return apiEncrypt != null || apiEncryptClass != null;
    }

    // 对返回值做包装处理，如果属于异常结果，则需要再包装
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter arg1, MediaType arg2,
                                  Class<? extends HttpMessageConverter<?>> arg3, ServerHttpRequest arg4, ServerHttpResponse arg5) {
        if (body instanceof HttpErrorResult) {
            HttpErrorResult error = (HttpErrorResult) body;
            return HttpResponseResult.fail(error.getCode(), error.getMessage(), error.getException());
        } else if (body instanceof HttpResponseResult) {
            return (HttpResponseResult) body;
        }
        return HttpResponseResult.success(body);
    }
}
